const path = require("path");
const mysql = require("mysql");
const express = require("express");
const cors = require("cors");
const request = require("request");
const bodyParser = require("body-parser");

const app = express();// 实例化 app
app.use(bodyParser.json()); // 处理 json 请求，post 请求
app.use(bodyParser.urlencoded({extended: false}));// 处理表单请求，get 请求
app.use(cors()); // 全局配置跨域
const router = express.Router();

// 文件配置，开启静态资源路径访问
const pathname = __dirname;
app.use(express.static(pathname));
app.use(express.static('oppo_broswer/dist'));

// mysql 配置
const option = {
    host: 'localhost',
    port: '3306',
    user: 'root',
    password: '344300zhd',
    database: 'oppo_broswer',
    connectTimeout: 5000, // 连接超时
}

// 连接池
let pool;
repool();

// 断线重连机制
function repool(){
    // 创建连接池
    pool = mysql.createPool({
        ...option,
        waitForConnections: true, //当无连接池可用时，等待（true）还是抛错（false）
        connectionLimit: 200, // 连接数限制
        queueLimit: 0, // 最大连接等待数，0 为不限制
    })
    pool.on('error', err => {
        err.code === 'PROTOCOL_CONNECTION_LOST' && setTimeout(repool, 2000)
    })
    app.all('*', (_, __, next) => {
        pool.getConnection(err => {
            err && setTimeout(repool, 2000) || next();
        })
    })
}

module.exports = {app, pool, router, request}